<template>
  <div class="app-main-content-box">
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="弹窗类型" prop="popType">
        <el-radio
          v-model="form.popType"
          @change="toGeneralPop"
          :label="1"
          :disabled="
            new Date(form.startTime).getTime() <= new Date().getTime() ||
            pageRoter.pageType === 'check' ||
            pageRoter.pageType === 'edit'
              ? true
              : false
          "
          >普通弹窗
        </el-radio>
        <el-radio
          v-model="form.popType"
          :label="2"
          @change="getPopStore"
          :disabled="
            new Date(form.startTime).getTime() <= new Date().getTime() ||
            pageRoter.pageType === 'check' ||
            pageRoter.pageType === 'edit'
              ? true
              : false
          "
          >储值弹窗</el-radio
        >
      </el-form-item>
      <!-- 标题 -->
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="form.title"
          type="text"
          maxlength="10"
          show-word-limit
          style="width: 30%"
          placeholder="请输入标题"
          :disabled="
            new Date(form.startTime).getTime() <= new Date().getTime() ||
            pageRoter.pageType === 'check'
              ? true
              : false
          "
        />
      </el-form-item>

      <!-- 有效期 -->
      <div>
        <el-form-item
          label="有效期"
          prop="validDate"
          v-if="
            new Date(form.startTime).getTime() <= new Date().getTime() &&
            pageRoter.pageType === 'edit'
          "
        >
          <el-date-picker
            v-model="form.startTime"
            align="center"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="开始日期"
            disabled
          />
          ~
          <el-date-picker
            v-model="form.endTime"
            align="center"
            type="datetime"
            placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item label="有效期" prop="validDate" v-else>
          <el-date-picker
            v-model="form.validDate"
            align="center"
            :default-time="defaultTime"
            type="datetimerange"
            range-separator="~"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="timerangeFn"
            :disabled="pageRoter.pageType === 'check'"
          />
        </el-form-item>
      </div>

      <!-- 弹窗图 -->
      <el-form-item label="弹窗图" prop="imgUrl" class="bigImg">
        <div
          v-if="
            form.popType === 1 ||
            pageRoter.pageType === 'check' ||
            new Date(form.startTime).getTime() <= new Date().getTime()
          "
          class="img-list"
        >
          <div class="img-item">
            <div class="handle-icon" v-if="isUpload">
              <i class="el-icon-zoom-in icon" @click="handlePreview()" />
              <i
                class="el-icon-delete icon"
                v-if="
                  (pageRoter.pageType === 'edit' && pageRoter.popState !== 2) ||
                  pageRoter.pageType === 'add'
                "
                @click="handleRemove()"
              />
            </div>
            <el-upload
              class="app-uploader-img-plus fl"
              :action="actionUrl"
              :show-file-list="false"
              :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :disabled="
                new Date(form.startTime).getTime() <= new Date().getTime() ||
                pageRoter.pageType === 'check'
                  ? true
                  : false
              "
            >
              <img
                v-if="form.imgUrl"
                :src="fileBaseUrl + form.imgUrl"
                class="avatar"
              />
              <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
            </el-upload>
          </div>
          <el-dialog
            :visible.sync="dialogVisible"
            style="width: 50%; margin-left: 50%"
          >
            <img style="width: 100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
          <ul class="upload_tips_img">
            <li>建议尺寸600*800px,大小1m内</li>
            <li>支持使用GIF格式</li>
          </ul>
        </div>
        <div
          v-if="
            form.popType === 2 &&
            (pageRoter.pageType === 'add' ||
              (pageRoter.pageType === 'edit' &&
                new Date(form.startTime).getTime() > new Date().getTime()))
          "
          class="img-list"
        >
          <div
            class="img-item"
            :class="{ activeImg: curIndex === index }"
            v-for="(item, index) in imgList"
            :key="index"
            @click="chooseImg(index)"
          >
            <div class="handle-icon">
              <i class="el-icon-zoom-in icon" @click="handlePreview()" />
              <!-- <i
                class="el-icon-delete icon"
                @click="handleRemoveStore(index)"
              /> -->
            </div>
            <el-upload
              class="app-uploader-img-plus fl"
              :action="actionUrl"
              :show-file-list="false"
              :headers="uploadHeaders"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :disabled="
                new Date(form.startTime).getTime() <= new Date().getTime() ||
                pageRoter.pageType === 'check'
                  ? true
                  : false
              "
            >
              <img
                :src="fileBaseUrl + item"
                class="avatar"
                style="max-width: 180px"
              />
            </el-upload>
          </div>
        </div>
        <el-dialog
          title="图片预览"
          :visible.sync="dialogImageVisible"
          style="width: 50%; margin-left: 20%"
        >
          <img style="width: 100%" :src="fileBaseUrl + form.imgUrl" alt />
        </el-dialog>
      </el-form-item>

      <!-- 站内链接 -->
      <el-form-item label="站内链接" :prop="form.popType === 1 ? 'path' : ''">
        <div v-if="form.popType === 1">
          <el-button
            size="small"
            @click="openInsideLink"
            :disabled="
              new Date(form.startTime).getTime() <= new Date().getTime() ||
              pageRoter.pageType === 'check'
                ? true
                : false
            "
            >选择链接</el-button
          >
          <div v-if="form.insideParams.remark">
            链接地址：{{ form.insideParams.remark }}
          </div>
        </div>
        <div v-else-if="form.popType === 2">余额充值</div>
      </el-form-item>

      <!-- 是否悬浮 -->
      <el-form-item label="是否悬浮" prop="isOver" class="suspend">
        <el-radio
          v-model="form.isOver"
          @change="vaildFn"
          :label="true"
          :disabled="
            new Date(form.startTime).getTime() <= new Date().getTime() ||
            pageRoter.pageType === 'check'
              ? true
              : false
          "
          >是</el-radio
        >
        <el-radio
          v-model="form.isOver"
          @change="vaildFn"
          :label="false"
          :disabled="
            new Date(form.startTime).getTime() <= new Date().getTime() ||
            pageRoter.pageType === 'check'
              ? true
              : false
          "
          >否</el-radio
        >
      </el-form-item>

      <!-- 悬浮小图 -->
      <!-- 有开启悬浮需要上传图片，支持GIF图 -->
      <el-form-item :prop="form.isOver === true ? 'overUrl' : ''">
        <div v-if="form.isOver === true">
          <el-upload
            class="app-uploader-img-plus uploader-small fl"
            :action="actionUrl"
            :show-file-list="false"
            :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
            :on-success="handleAvatarSuccessSm"
            :before-upload="beforeAvatarUploadSuspend"
            :disabled="
              new Date(form.startTime).getTime() <= new Date().getTime() ||
              pageRoter.pageType === 'check'
                ? true
                : false
            "
          >
            <div>
              <img
                v-if="form.overUrl"
                :src="fileBaseUrl + form.overUrl"
                class="avatar-small"
              />
              <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
            </div>
          </el-upload>
          <ul class="upload_tips">
            <li>建议尺寸200*200px,大小1m内</li>
            <li>支持使用GIF格式</li>
            <li class="suspend-css" v-if="form.popType === 2">
              <el-button
                type="text"
                @click="resume"
                :disabled="
                  form.overUrl === overImgList[this.curIndex] ? true : false
                "
                >恢复样式</el-button
              >
            </li>
          </ul>
        </div>
        <div v-else></div>
      </el-form-item>

      <!-- 显示设置 -->
      <el-form-item label="显示设置" prop="showRule">
        <el-radio
          v-model="form.showType"
          :label="1"
          :disabled="
            new Date(form.startTime).getTime() <= new Date().getTime() ||
            pageRoter.pageType === 'check'
              ? true
              : false
          "
        >
          <el-input
            type="text"
            v-model="form.showTimes"
            style="width: 100px; display: none"
            size="small"
            :disabled="
              new Date(form.startTime).getTime() <= new Date().getTime() ||
              pageRoter.pageType === 'check'
                ? true
                : false
            "
          />
          每次进入店铺显示</el-radio
        >
        <el-radio
          v-model="form.showType"
          :label="2"
          :disabled="
            new Date(form.startTime).getTime() <= new Date().getTime() ||
            pageRoter.pageType === 'check'
              ? true
              : false
          "
        >
          <el-input
            type="text"
            v-model="form.showRadio"
            style="width: 100px"
            size="small"
            :disabled="
              new Date(form.startTime).getTime() <= new Date().getTime() ||
              pageRoter.pageType === 'check'
                ? true
                : false
            "
          />天显示一次
        </el-radio>
      </el-form-item>

      <el-form-item>
        <el-button @click="cancelFn" :disabled="false">取消</el-button>
        <el-button
          v-if="pageRoter.pageType === 'add' || pageRoter.pageType === 'edit'"
          type="primary"
          @click="savePop"
          :disabled="false"
          >保存</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 站内链接弹窗 -->
    <DialogInsideLink ref="insideLink" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import DialogInsideLink from '@/views/wxaBuildModule/views/components/DialogInsideLink'
import { imgUploadUrl } from '@/api/upload'
import {
  PopConfigListAdd,
  PopConfigPicList,
  getPopById,
  PopConfigListUpdate
} from '@/api/marketing'
export default {
  components: {
    DialogInsideLink
  },
  data() {
    const disabledDate = (date) => {
      return date.getTime() < new Date().getTime() - 86400000
    }
    return {
      loading: false,
      pageRoter: this.$route.query,
      isUpload: false,
      isShowRemove: true,
      actionUrl: imgUploadUrl, // 图片下载路径
      dialogImageVisible: false,
      dialogVisible: false,
      dialogImageUrl: '',
      uploadHeaders: {},
      pickerOptions: {
        // 筛选日期
        disabledDate
        // selectableRange 用来限制时分秒的选择，这里要求只能选择当前时间之后到0点的时间点 但应该只限今天
        // selectableRange: '00:00:00 - 23:59:59'
      },
      imgList: [], // 弹窗图列表
      overImgList: [], // 悬浮图
      curIndex: 0, // 默认选中第一张图
      defaultTime: [],
      time: '',
      // 表单
      form: {
        appId: '',
        feature: '',
        featureParams: '',
        insidePage: '',
        insideParams: '',
        path: '',
        type: 'INSIDE',
        url: '',
        id: null,
        popType: 1,
        title: '',
        validDate: [],
        startTime: '',
        endTime: '',
        imgUrl: '',
        isOver: true,
        overUrl: '',
        showRule: null,
        showRadio: null,
        showType: 1,
        showTimes: null
      },
      // 表单校验
      rules: {
        popType: [
          {
            required: true,
            message: '请选择弹窗的类型',
            trigger: ['blur', 'change']
          }
        ],
        title: [
          {
            required: true,
            message: '请填写标题',
            trigger: ['blur', 'change']
          },
          {
            min: 1,
            max: 10,
            message: '请输入1到10位之间',
            trigger: ['blur', 'change']
          }
        ],
        validDate: [
          {
            required: true,
            message: '请选择弹窗的有效日期',
            trigger: ['change']
          }
        ],
        isOver: [
          {
            required: true,
            message: '请选择是否悬浮',
            trigger: ['change']
          }
        ],
        imgUrl: [
          {
            required: true,
            message: '请选择弹窗图',
            trigger: ['blur', 'change']
          }
        ],
        showRule: [
          {
            required: true,
            message: '请选择显示设置',
            trigger: ['blur', 'change']
          }
        ],
        overUrl: [
          {
            required: true,
            message: '请选择弹窗图',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },

  computed: {
    ...mapGetters(['fileBaseUrl'])
  },

  created() {
    this.getTimeFun()
  },

  mounted() {
    this.fetchData()
  },

  methods: {
    // 获取当前时间
    getTimeFun() {
      const yy = new Date().getFullYear()
      const mm = new Date().getMonth() + 1
      const dd = new Date().getDate()
      const hh = new Date().getHours()
      const mf =
        new Date().getMinutes() < 10
          ? '0' + new Date().getMinutes() + 5
          : new Date().getMinutes() + 5
      const ss =
        new Date().getSeconds() < 10
          ? '0' + new Date().getSeconds()
          : new Date().getSeconds()
      this.time = hh + ':' + mf + ':' + ss
      this.defaultTime = [this.time, '23:59:59']
    },

    // 站内链接
    openInsideLink() {
      this.$refs.insideLink.open({ row: this.form }).then((res) => {
        console.log(3333, res)
        this.form.insidePage = res.insidePage || null
        this.form.insideParams = {
          insidePageType: res.insideParams.insidePageType || null,
          pageId: (res.insideParams && res.insideParams.pageId) || null,
          goodsSerial:
            (res.insideParams && res.insideParams.goodsSerial) || null,
          commonCode: (res.insideParams && res.insideParams.commonCode) || null,
          remark: (res.insideParams && res.insideParams.remark) || null
        }
        this.form.mode = res.mode || null
        this.form.path = res.path || null
      })
      console.log(1111, this.form)
    },

    handleAvatarSuccess(res, file) {
      if (res.code === 0) {
        this.isUpload = true
        this.form.imgUrl = res.data.path
        this.$refs.form.clearValidate(['imgUrl'])
      } else {
        this.$message.error(res.msg)
      }
    },
    handleAvatarSuccessSm(res, file) {
      if (res.code === 0) {
        this.form.overUrl = res.data.path
        this.$refs.form.clearValidate(['overUrl'])
      } else {
        this.$message.error(res.msg)
      }
    },
    // 上传预处理
    beforeAvatarUpload(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1, ['JPG', 'PNG', 'GIF'])
    },
    beforeAvatarUploadSuspend(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1, ['JPG', 'PNG', 'GIF'])
    },
    // 删除图片
    handleRemove(file) {
      this.form.imgUrl = ''
      this.isUpload = false
    },

    // 图片放大
    handlePreview(file) {
      console.log(file, 555555)
      // this.dialogImageUrl = file.
      this.dialogImageVisible = true
    },

    // 有效时间限制
    timerangeFn(val) {
      this.form.startTime = val[0]
      this.form.endTime = val[1]
      const startTime = new Date(val[0])
      const curTime = new Date()
      if (this.pageRoter.pageType === 'add') {
        if (startTime.getTime() <= curTime.getTime()) {
          this.$message.warning('有效期不可选择已过时间')
          this.form.validDate = ''
          return
        }
      } else {
        return this.form.validDate
      }
    },

    // 恢复样式
    resume() {
      this.form.overUrl = this.overImgList[this.curIndex]
    },

    // 获取弹窗图列表
    async getPopStore() {
      if (this.pageRoter.pageType === 'add') {
        this.form.imgUrl = ''
        this.form.overUrl = ''
        this.form.title = ''
        this.form.validDate = []
        this.isUpload = false
      }
      const res = await PopConfigPicList()
      this.imgList = res.data.backgroundUrl
      this.overImgList = res.data.overImgUrl
      this.curIndex = this.imgList.findIndex(
        (item) => item === this.form.imgUrl
      )
    },

    // 清空储值弹窗的图片联动
    async toGeneralPop() {
      this.form.imgUrl = ''
      this.form.overUrl = ''
      this.form.title = ''
      this.form.validDate = []
      await this.$refs.form.clearValidate()
    },

    // 切换单选时清空校验
    vaildFn() {
      this.$refs.form.clearValidate()
    },

    //  选中的大图片
    chooseImg(index) {
      this.curIndex = index
      this.form.imgUrl = this.imgList[index]
      this.form.overUrl = this.overImgList[index]
    },

    // 编辑查看数据回填
    async fetchData() {
      // console.log(656, this.isUpload);

      this.form.id = this.pageRoter.id
      if (
        this.pageRoter.pageType === 'edit' ||
        this.pageRoter.pageType === 'check'
      ) {
        this.isUpload = true
        const res = await getPopById(this.form.id)
        this.form = res.data
        this.form.insideParams = JSON.parse(this.form.insideParams)
        console.log(21111, this.form)

        if (res.data.popType === 2) {
          this.imgList = this.getPopStore()
          this.form.imgUrl = res.data.imgUrl
          this.form.overUrl = res.data.overUrl
        }
        if (res.data.showType === 1) {
          if (res.data.showRule === 0) {
            this.form.showTimes = null
          } else {
            this.form.showRadio = null
          }
        } else if (res.data.showType === 2) {
          this.form.showRadio = Number(res.data.showRule)
        }
        console.log(486, this.form.showRadio)

        let dateList = [res.data.startTime, res.data.endTime]
        this.$set(this.form, 'validDate', dateList)
      }
    },

    // 弹窗新增编辑查看
    async savePop() {
      if (this.form.showType === 1) {
        this.form.showRule = 0
      } else if (this.form.showType === 2) {
        this.form.showRule = Number(this.form.showRadio)
      }
      await this.$refs.form.validate()
      this.loading = true
      // 发情求
      if (this.pageRoter.pageType === 'add') {
        // 普通弹窗
        if (this.form.popType === 1) {
          console.log('新增', this.form)
          const res = await PopConfigListAdd({
            ...this.form,
            insideParams: JSON.stringify(this.form.insideParams)
          })

          console.log(500151, res)
          if (res.code === 0) {
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
            this.loading = false
            this.$router.push({ name: 'MarketingActivityDialog' })
          } else {
            this.loading = false
            this.$message.error(res.msg)
          }
        } else {
          // 储值弹窗
          const insideParams = {
            remark: '余额充值',
            goodsSerial: null
          }
          const res = await PopConfigListAdd({
            ...this.form,
            path: '/pages/memberCardModule/pages/balanceRecharge/main',
            insideParams: JSON.stringify(insideParams)
          })
          if (res.code === 0) {
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
            this.loading = false
            this.$router.push({ name: 'MarketingActivityDialog' })
          } else {
            this.loading = false
            this.$message.error(res.msg)
          }
        }
      } else if (this.pageRoter.pageType === 'edit') {
        const res = await PopConfigListUpdate({
          ...this.form,
          insideParams: JSON.stringify(this.form.insideParams)
        })

        if (res.code === 0) {
          this.$notify({
            title: '成功',
            message: '编辑成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })

          this.loading = false
          this.$router.push({ name: 'MarketingActivityDialog' })
        } else {
          this.loading = false
          this.$message.error(res.msg)
        }
      }
    },

    // 取消
    cancelFn() {
      this.$router.push({ name: 'MarketingActivityDialog' })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.suspend {
  margin-bottom: 0;
}
.el-button {
  padding: 12px 50px;
}

.app-uploader-img-plus ::v-deep {
  margin-right: 20px;
  width: 180px;
  height: 180px;
  .el-upload--picture-card {
    width: 180px;
    height: 180px;
    border: none;
  }

  .app-uploader-img-plus-icon {
    font-size: 36px;
    color: #8c939d;
    width: 180px;
    height: 180px;
    line-height: 180px;
    text-align: center;
  }
  .avatar {
    width: 180px;
    height: 180px;
    display: block;
  }
}

// 小图
.uploader-small {
  margin-right: 20px;
  width: 100px;
  height: 100px;
  .app-uploader-img-plus-icon {
    font-size: 26px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar-small {
    width: 98px;
    height: 98px;
    display: block;
  }
}

.upload_tips {
  margin: 20px 0 0 20px;
  li {
    margin-top: 10px;
    font-size: 14px;
    line-height: 16px;
    color: $dark-font-color;
    .el-button {
      padding: 0;
    }
  }
}

.bigImg {
  .img-list {
    position: relative;
    margin: 0;
    vertical-align: top;
    cursor: pointer;
    .upload_tips_img {
      position: absolute;
      top: 14px;
      left: 190px;
      margin: 20px 0 0 20px;
      li {
        margin-top: 10px;
        font-size: 14px;
        line-height: 16px;
        color: $dark-font-color;
      }
    }
    .activeImg {
      width: 184px !important;
      height: 184px !important;
      border: 4px solid #ffb72f !important;
    }
    .img-item {
      position: relative;
      overflow: hidden;
      background-color: #fff;
      border: 1px solid #c0ccda;
      border-radius: 6px;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      height: 180px;
      width: 180px;
      margin: 0 8px 8px 0;
      display: inline-block;
      border: none;
      .handle-icon {
        display: none;
      }
      &:hover {
        font-size: 20px;
        color: #fff;
        .handle-icon {
          position: absolute;
          top: 0;
          left: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.5);

          z-index: 999;
          .icon {
            margin: 10px;
          }
        }
      }
    }
  }
}
</style>
